package org.liu.trace;

import com.alibaba.fastjson.JSON;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.hyperledger.fabric.contract.Context;
import org.hyperledger.fabric.contract.ContractInterface;
import org.hyperledger.fabric.contract.annotation.*;
import org.hyperledger.fabric.shim.ChaincodeException;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.liu.trace.util.JDBCUtil;

import java.util.List;
import java.util.Random;

/**
 * @author : lyj
 * @Timer : 2024/3/26
 * @Description :
 */
@Contract(
        name = "RecordContract",
        info = @Info(
                title = "Record Contract",
                description = "The hyperlegendary record contract",
                version = "0.0.1-SNAPSHOT",
                license = @License(
                        name = "Apache 2.0 License",
                        url = "http://www.apache.org/licenses/LICENSE-2.0.html"),
                contact = @Contact(
                        email = "f.record@example.com",
                        name = "Liu yingJie",
                        url = "https://hyperledger.example.com")))
@Default
@Log
public class RecordContract implements ContractInterface {

    @Transaction
    public void initLedger(final Context ctx) {
        ChaincodeStub stub = ctx.getStub();
        List<Record> recordList = JDBCUtil.getRecordList();
        recordList.stream().forEach(record -> {
            stub.putStringState(String.valueOf(record.getId()), JSON.toJSONString(record));
        });
        //for (int i = 0; i < 10; i++) {
        //    Record record = new Record().setRemarks("record-" + i)
        //            .setId(i)
        //            .setProId(new Random().nextInt())
        //            .setUserId(new Random().nextInt())
        //            .setImg("img" + i + ".png")
        //            .setLocation("南京" + i);
        //    // Remarks是key
        //    stub.putStringState(record.getRemarks(), JSON.toJSONString(record));
        //}
    }

    @Transaction
    public Record queryRecord(final Context ctx, final String key) {

        ChaincodeStub stub = ctx.getStub();
        String recordState = stub.getStringState(key);

        if (StringUtils.isBlank(recordState)) {
            String errorMessage = String.format("Record %s does not exist", key);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        return JSON.parseObject(recordState, Record.class);
    }

    @Transaction
    public Record createRecord(final Context ctx, final String key, Integer proId, Integer userId, String location, String img) {

        ChaincodeStub stub = ctx.getStub();
        String recordState = stub.getStringState(key);

        if (StringUtils.isNotBlank(recordState)) {
            String errorMessage = String.format("Cat %s already exists", key);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        Record record = new Record();
        record.setProId(proId)
                .setUserId(userId)
                .setLocation(location)
                .setImg(img);

        String json = JSON.toJSONString(record);
        stub.putStringState(key, json);

        stub.setEvent("createRecordEvent", org.apache.commons.codec.binary.StringUtils.getBytesUtf8(json));
        return record;
    }

    @Transaction
    public Record updateRecord(final Context ctx, final String key, Integer proId, Integer userId, String location, String img) {
        ChaincodeStub stub = ctx.getStub();
        String catState = stub.getStringState(key);

        if (StringUtils.isBlank(catState)) {
            String errorMessage = String.format("Record %s does not exist", key);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }
        Record record = new Record();
        record.setProId(proId)
                .setUserId(userId)
                .setLocation(location)
                .setImg(img);
        stub.putStringState(key, JSON.toJSONString(record));

        return record;
    }

    @Transaction
    public Record deleteRecord(final Context ctx, final String key) {

        ChaincodeStub stub = ctx.getStub();
        String recordState = stub.getStringState(key);

        if (StringUtils.isBlank(recordState)) {
            String errorMessage = String.format("Record %s does not exist", key);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        stub.delState(key);

        return JSON.parseObject(recordState, Record.class);
    }


    @Override
    public void beforeTransaction(Context ctx) {
        log.info("*************************************** beforeTransaction ***************************************");
    }

    @Override
    public void afterTransaction(Context ctx, Object result) {
        log.info("*************************************** afterTransaction ***************************************");
        System.out.println("result --------> " + result);
    }
}
